
package com.joysuch.wwyt.dataperm.aop;

import java.lang.annotation.Annotation;

import com.joysuch.wwyt.dataperm.annotation.DisableDataPermission;
import com.joysuch.wwyt.dataperm.annotation.EnableDataPermission;
import com.joysuch.wwyt.dataperm.context.DataPermContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class AopDataPermProcessor {

    private static final Logger logger = LoggerFactory.getLogger(AopDataPermProcessor.class);

    public AopDataPermProcessor() {
    }

    /**
     * 拦截DisableDataPermission标注的方法，在当前上下文中关闭数据权限拦截
     * 
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(com.joysuch.wwyt.dataperm.annotation.DisableDataPermission)")
    public Object disableDataPermAnnotation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        boolean isRecursive = isRecursivePermission(proceedingJoinPoint, DisableDataPermission.class);
        logger.debug("DisableDataPermission -> {} -> {}", proceedingJoinPoint.getStaticPart(), isRecursive);
        DataPermContextHolder.pushCurrentDataPermSwitch(false, isRecursive);
        try {
            return proceedingJoinPoint.proceed();
        } finally {
            DataPermContextHolder.popDataPermSwitch();
        }
    }

    /**
     * 拦截EnableDataPermission标注的方法，在当前上下文中关闭数据权限拦截
     * 
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(com.joysuch.wwyt.dataperm.annotation.EnableDataPermission)")
    public Object enableDataPermAnnotation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        boolean isRecursive = isRecursivePermission(proceedingJoinPoint, EnableDataPermission.class);
        logger.debug("EnableDataPermission -> {} -> {}", proceedingJoinPoint.getStaticPart(), isRecursive);
        DataPermContextHolder.pushCurrentDataPermSwitch(true, isRecursive);
        try {
            return proceedingJoinPoint.proceed();
        } finally {
            DataPermContextHolder.popDataPermSwitch();
        }
    }

    private boolean isRecursivePermission(ProceedingJoinPoint proceedingJoinPoint, Class annotation) {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Annotation an = signature.getMethod().getAnnotation(annotation);
        if (an.annotationType() == DisableDataPermission.class) {
            return ((DisableDataPermission) an).recursive();
        } else if (an.annotationType() == EnableDataPermission.class) {
            return ((EnableDataPermission) an).recursive();
        }
        throw new IllegalArgumentException("错误的注解类型: " + annotation);
    }

}
